package org.edu.modules.oa.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.SecurityUtils;
import org.edu.common.api.vo.Result;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.vo.LoginUser;
import org.edu.common.util.RedisUtil;
import org.edu.modules.oa.config.QueryConditionTool;
import org.edu.modules.oa.entity.VeOaCarInfoEntity;
import org.edu.modules.oa.entity.VeOaCarShiYongEntity;
import org.edu.modules.oa.entity.VeOaCarWeihuEntity;
import org.edu.modules.oa.service.IVeOaCarWeihuService;
import org.edu.modules.oa.util.OssDownloadUtil;
import org.edu.modules.oa.vo.QueryCondition;
import org.edu.modules.oa.vo.VeOaCarInfoTableVo;
import org.edu.modules.oa.vo.VeOaCarWeihuVo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags="车辆维护记录")
@RestController
@RequestMapping("oa/veOaCarWeihu")
@Slf4j
public class VeOaCarWeihuController {
    @Resource//注入
    private IVeOaCarWeihuService iVeOaCarWeihuService;
    @Autowired
    private RedisUtil redisUtil; // redis服务类
    //日志注解
    @AutoLog(value = "车辆维护-显示表格")
    //(value = “接口说明”, httpMethod = “接口请求方式”, response = “接口返回参数类型”, notes = “接口发布说明”）
    @ApiOperation(value="显示表格", notes="车辆维护-显示表格")
    //映射一个POST请求
    @PostMapping(value = "/showShiguTable")
    //展示表格
    public Result<?>showTable(Integer page, Integer pageSize, VeOaCarWeihuEntity veOaCarWeihuEntity){
        HashMap<String, Object> map = iVeOaCarWeihuService.showWeiHuTable(page,pageSize,veOaCarWeihuEntity);
        return Result.ok(map);
    }

    //添加
    @AutoLog(value = "车辆维护记录-添加数据")
    @ApiOperation(value = "添加数据", notes = "车辆维护-添加数据")
    @PostMapping(value = "/addWeihuTable")
    public Result<?>addTable(VeOaCarWeihuEntity veOaCarWeihuEntity,String date)throws ParseException {
        // 前端传过来的时间字符串转换成日期
        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date sTime= null;
        sTime = formatter.parse(date.trim());
        veOaCarWeihuEntity.setWeihuDate(sTime);
        //获取登陆人的信息
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        veOaCarWeihuEntity.setCreateBy(user.getId());
        veOaCarWeihuEntity.setCreateByName(user.getRealname());
        veOaCarWeihuEntity.setTerminalId(1);//终端ID
        int res = iVeOaCarWeihuService.addWeihu(veOaCarWeihuEntity);
        if(res==0){
            return Result.error(500,"添加失败");
        }
        return Result.ok();
    }
    //删除单条
    @PostMapping(value = "/deletById")
    public Result<?>deleteById(Integer id){
        int res = iVeOaCarWeihuService.deletById(id);
        if(res==0){
            //删除失败
            return Result.error(500,"删除失败");
        }
        return Result.OK("删除成功");
    }


    //删除多条
    @RequestMapping("/deletWeihuAll")
    public Result<?>deleteAll(String idAll) {
        if (idAll != null || idAll != "") {
            //切割逗号，转成数组
            String[] arr = idAll.split(",");
            for (int i = 1; i < arr.length; i++) {
                iVeOaCarWeihuService.deletById(Integer.parseInt(arr[i]));
            }

        }
        return Result.ok();
    }


    //导出
    @AutoLog(value = "车辆维护-导出excel表格")
    @ApiOperation(value = "导出excel表格", notes = "车辆加维护-导出excel表格")
    @RequestMapping(value = "/exportWeihuTable")
    public ModelAndView exportTable(){
        VeOaCarWeihuEntity veOaCarWeihuEntity =new VeOaCarWeihuEntity();

        //创建导出流
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //查数据获得维护表格的集合
        List<VeOaCarWeihuVo> list = iVeOaCarWeihuService.export(veOaCarWeihuEntity);
        //文件的文件名
        mv.addObject(NormalExcelConstants.FILE_NAME,"车辆维护记录");
        //数据的类型
        mv.addObject(NormalExcelConstants.CLASS,VeOaCarWeihuVo.class);
        //获取redis存的用户值
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // ExportParams  Export工具类   （参数1--》title:表格标题  参数2--》secomdTitle:第二行的标题，  参数3--》secomdTitle:最下面尾部的信息）
        ExportParams exportParams = new ExportParams("车辆违章事故记录", "导出人:" + user.getRealname(), "导出违章事故辆加油记录");
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, list);
        return mv;
    }

    //单个导出
    @AutoLog(value = "车辆维护-单个导出excel表格")
    @ApiOperation(value = "单个导出excel表格", notes = "车辆加维护-单个导出excel表格")
    @RequestMapping(value = "/exportWeihuTableOne")
    public ModelAndView exportWeihuTableOne(){
        VeOaCarWeihuEntity veOaCarWeihuEntity =new VeOaCarWeihuEntity();

        VeOaCarInfoTableVo vo = (VeOaCarInfoTableVo) redisUtil.get("carInfo");

        veOaCarWeihuEntity.setCarId(vo.getId() );
        //创建导出流
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //查数据获得维护表格的集合
        List<VeOaCarWeihuVo> list = iVeOaCarWeihuService.export(veOaCarWeihuEntity);
        //文件的文件名
        mv.addObject(NormalExcelConstants.FILE_NAME,"车辆维护记录");
        //数据的类型
        mv.addObject(NormalExcelConstants.CLASS,VeOaCarWeihuVo.class);
        //获取redis存的用户值
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // ExportParams  Export工具类   （参数1--》title:表格标题  参数2--》secomdTitle:第二行的标题，  参数3--》secomdTitle:最下面尾部的信息）
        ExportParams exportParams = new ExportParams("车辆违章事故记录", "导出人:" + user.getRealname(), "导出违章事故辆加油记录");
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, list);
        return mv;
    }

    //list
    @AutoLog(value = "车辆维护-导出excel表格")
    @ApiOperation(value = "导出excel表格", notes = "车辆维护-导出excel表格")
    @RequestMapping(value = "/list")
    public ModelAndView exportTableTest(){
        VeOaCarWeihuEntity veOaCarWeihuEntity =new VeOaCarWeihuEntity();

        //创建导出流
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //查数据获得维护表格的集合
        List<VeOaCarWeihuVo> list = iVeOaCarWeihuService.export(veOaCarWeihuEntity);
        //文件的文件名
        mv.addObject(NormalExcelConstants.FILE_NAME,"车辆维护记录");
        //数据的类型
        mv.addObject(NormalExcelConstants.CLASS,VeOaCarWeihuVo.class);
        //获取redis存的用户值
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // ExportParams  Export工具类   （参数1--》title:表格标题  参数2--》secomdTitle:第二行的标题，  参数3--》secomdTitle:最下面尾部的信息）
        ExportParams exportParams = new ExportParams("车辆违章事故记录", "导出人:" + user.getRealname(), "导出违章事故辆加油记录");
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, list);
        return mv;
    }


    //导入
    @AutoLog(value = "车辆维护-导入")
    @ApiOperation(value = "导入", notes = "车辆维护-导入")
    @PostMapping(value = "/importExcel")
    public Result<?>importExcel(HttpServletRequest req, HttpServletResponse resp){
        //先把需要导入的文件上传
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
        //获取上传的文件
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        //取出来
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                //上传的数据的集合(list就是文件里所有内容)
                List<VeOaCarWeihuVo> list = ExcelImportUtil.importExcel(file.getInputStream(), VeOaCarWeihuVo.class, params);
                System.out.println("================"+list.size()+"================");
                // 获取redis存的用户值
                LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                //加入数据库使用的集合
                List<VeOaCarWeihuEntity> entityList =new ArrayList<>();
                //循环遍历把需要的字段拷贝到数据库插入的集合中
                for(VeOaCarWeihuVo v : list){
                    System.out.println("=============================");
                    System.out.println(v);
                    System.out.println("=============================");
                    VeOaCarWeihuEntity veOaCarWeihuEntity = new VeOaCarWeihuEntity();
                    //查看车辆名字数据库是否存在
                    VeOaCarInfoEntity veOaCarInfoEntity = iVeOaCarWeihuService.selectCarId(v.getCarName());
                    if(null == veOaCarInfoEntity){
                        return Result.error("文件导入失败: 没有这辆车！" );
                    }
                    veOaCarWeihuEntity.setCarName(veOaCarInfoEntity.getCarName());
                    // 字符串转换成时间类型
                    SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    veOaCarWeihuEntity.setWeihuDate(formatter.parse(v.getWeihuDate()));
                    veOaCarWeihuEntity.setWeihuType(v.getWeihuType());
                    veOaCarWeihuEntity.setJingbanUser(v.getJingbanUser());
                    veOaCarWeihuEntity.setWeihuContent(v.getWeihuContent());
                    veOaCarWeihuEntity.setWeihuFeiyong(v.getWeihuFeiyong());
                    veOaCarWeihuEntity.setBackInfo(v.getBackInfo());
//                    veOaCarWeihuEntity.setCreateBy(v.getCreateBy());
//                    veOaCarWeihuEntity.setCreateByName(v.getCreateByName());
//                    veOaCarWeihuEntity.setCreateTime(formatter.parse(v.getCreateTime()));
//                    veOaCarWeihuEntity.setUpdateBy(v.getUpdateBy());
//                    veOaCarWeihuEntity.setUpdateByName(v.getUpdateByName());
//                    veOaCarWeihuEntity.setUpdateTime(formatter.parse(v.getUpdateTime()));
                    entityList.add(veOaCarWeihuEntity);
                }
                iVeOaCarWeihuService.saveBatch(entityList);
                return Result.ok("文件导入成功！数据行数：" + entityList.size());
            } catch (Exception e) {
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    //修改
    @AutoLog(value = "车辆维护-修改")
    @ApiOperation(value = "修改", notes = "车辆维护-修改")
    @PostMapping(value = "/setWeihuTable")
    public Result<?>setTable(VeOaCarWeihuEntity veOaCarWeihuEntity,String date)throws ParseException{
        // 前端传过来的时间字符串转换成日期
        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date sTime= null;
        sTime = formatter.parse(date.trim());
        veOaCarWeihuEntity.setWeihuDate(sTime);
        //获取登陆人的信息
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        veOaCarWeihuEntity.setUpdateBy(user.getId());
        veOaCarWeihuEntity.setUpdateByName(user.getRealname());

        int res = iVeOaCarWeihuService.setWeihu(veOaCarWeihuEntity);
        if(res==0){
            return Result.error(500,"修改失败");
        }
        return Result.ok();
    }

    // 高级搜索
//    @AutoLog(value = "车辆违章事故记录-高级搜索")
    @AutoLog(value = "车辆维护记录-高级搜索") //李少君
//    @ApiOperation(value="高级搜索", notes="车辆违章事故记录-高级搜索")
    @ApiOperation(value="高级搜索", notes="车辆维护记录-高级搜索") //李少君
    @PostMapping(value = "/advancedQuery")
    public Result advancedQuery(@RequestBody String queryArray) {
        Map<String, List<QueryCondition>> maps = (Map<String, List<QueryCondition>>) JSON.parse(queryArray);
        List<QueryCondition> list=new ArrayList<QueryCondition>(JSONArray.parseArray(maps.get("queryArray").toString(),QueryCondition.class));
        String  conditionStr =  QueryConditionTool.getQueryConditionTool().advancedQuery(list);
        HashMap<String , Object>  map=null;
        map = iVeOaCarWeihuService.advancedQuery(conditionStr);
        return  Result.OK(map);
    }
    //获取模板下载地址
    @AutoLog(value = "车辆维护-模板地址获取")
    @ApiOperation(value = "模板地址", notes = "车辆维护-模板地址获取")
    @PostMapping(value = "/getUrl")
    public Result<T> getUrl() throws Exception {
        Result result = new Result();
        String url= OssDownloadUtil.getOssDownloadUtil().downFileFromOSS("车辆维护记录模板.xls");
        result.success(url);
        return result;
    }
}
